package com.github.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * user:wangj
 * date:2018/7/22
 * Time: 20:49
 */
@Component
public class ZuulGatewayFilter extends ZuulFilter {

    @Value("${server.custom.token.header.token-header}")
    private String tokenHeader;

    @Value("${server.custom.token.header.client-id}")
    private String clientId;

    private static final Logger log=LoggerFactory.getLogger(ZuulGatewayFilter.class);

    //定义filter的类型，有pre、route、post、error四种
    @Override
    public String filterType() {
        return "pre";
    }

    //定义filter的顺序，数字越小表示顺序越高，越先执行
    @Override
    public int filterOrder() {
        return 1;
    }

    //表示是否需要执行该filter，true表示执行，false表示不执行
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //filter需要执行的具体操作
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token=request.getHeader(tokenHeader);
        String client_Id=request.getHeader(clientId);
        //todo:: 这里设置路由规则可从数据库中读取
        /*if(StringUtils.isEmpty(token)||StringUtils.isEmpty(client_Id)){
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }*/
        log.info("ok");
        return null;
    }
}
